package com.exampl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exampl.common.R;
import com.exampl.domain.Employee;
import com.exampl.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // 登录
    @PostMapping("/login")
    public R<Employee> Login(HttpServletRequest request, @RequestBody Employee employee){
        String password = employee.getPassword();
        // 加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<Employee>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        // 查询
        Employee employee1 = employeeService.getOne(lqw);
        // 未查询到，登陆失败
        if(employee1 == null){
            return R.error("登陆失败！");
        }
        // 密码匹配不上，登陆失败
        if(!password.equals(employee1.getPassword())){
            return R.error("登陆失败！");
        }
        // 被禁用
        if(employee1.getStatus() == 0){
            return R.error("该账号已禁用！");
        }
        // 登陆成功
        request.getSession().setAttribute("employee", employee1.getId());
        return R.success(employee1);
    }

    // 退出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        // 清除id值
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }

    // 显示员工信息
    @GetMapping("/page")
    public R<IPage<Employee>> page(int page, int pageSize, String name){
        IPage<Employee> iPage = employeeService.getPage(page, pageSize, name);
        return R.success(iPage);
    }

    // 添加员工
    @PostMapping
    public R<String> add(@RequestBody Employee employee){
        // 设置初始密码:123456，进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("员工创建成功！");
    }

    // 修改信息，包括状态与具体信息
    @PutMapping
    public R<String> updateStatus(@RequestBody Employee employee){
        employeeService.updateById(employee);
        return R.success("修改成功！");
    }

    // 回显信息
    @GetMapping("/{id}")
    public R<Employee> reserve(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
